import { useNavigateStore } from '@/store/modules/useNavigate'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = []

const modules: any = import.meta.glob('./modules/*.ts', { eager: true })
for (const path in modules) {
  if (path == './modules/system.ts') continue

  if (Array.isArray(modules[path].default)) {
    modules[path].default.map((v: any) => routes.push(v))
  } else {
    routes.push(modules[path].default)
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
  strict: false,
})

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  const navigateStore = useNavigateStore()

  const hasToken = localStorage.getItem('XUAN_ADMIN_TOKEN')

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const hasRoles = navigateStore.roles && navigateStore.routes.length > 0

      if (hasRoles) {
        next()
      } else {
        const asnycRoute = navigateStore.generateRoutes()

        asnycRoute.map((res) => {
          router.addRoute(res)
        })

        if (to.path == '/404' && to.redirectedFrom != undefined) {
          next({ path: to.redirectedFrom?.fullPath, replace: true })
        } else {
          next({ ...to, replace: true })
        }
      }
    }
  } else {
    whiteList.includes(to.path) ? next() : next('/login')
  }
})

router.afterEach(() => {})

export default router
